package com.bobbygu.googlearchitecture.database

import android.arch.lifecycle.LiveData
import android.arch.persistence.room.Room
import android.content.Context
import android.util.Log
import com.bobbygu.googlearchitecture.bean.Story

/**
 *
 * # time: 2017/12/20 8:49
 * # e-mail: gubojun@csii.com.cn
 * @author 顾博君
 * @since 1.0
 */
object DatabaseManager {
    private lateinit var db: AppDatabase
    fun initDb(context: Context) {
        db = Room.databaseBuilder(context, AppDatabase::class.java, AppDatabase.TAG).build()
    }

    fun insertStories(stories: List<Story>) {
        Thread({
            db.beginTransaction()
            try {
                db.storyDao().insertStories(stories)
                db.setTransactionSuccessful()
            } finally {
                db.endTransaction()
            }
        }).start()
    }

    fun insertStory(story: Story) {
        Thread({
            db.beginTransaction()
            try {
                db.storyDao().insertStories(story)
                db.setTransactionSuccessful()
            } finally {
                db.endTransaction()
            }
        }).start()
    }

    fun deleteAllStories(): Int {
        return db.storyDao().deleteAllStories()
    }

    fun deleteStory() {
        Thread({
            val stories = getAllStories()
            Log.d("delete", stories.toString())
            if (stories.isNotEmpty()) {
                db.storyDao().deleteStories(stories[0])
            }
        }).start()
    }

    fun getAllStories(): List<Story> {
        return db.storyDao().getAllStories()
    }

    fun loadAllStories(): LiveData<List<Story>> {
        return db.storyDao().loadAllStories()
    }

    fun simlutateInsertData() {
        val list = ArrayList<Story>()

        for (i in 1..20) {
            val s = Story()
            s.id = (i)
            s.data = "bobby-" + i.toString()
            s.displayData = "bobby-" + i.toString()
            s.title = "bobby-" + i.toString()
            list.add(s)
        }
        insertStories(list)
    }
}